package linuxshell

import (
	"bufio"
	"io"
	"os/exec"
	"sync"
)

const (
	shellGrepF = " | grep %s"
)

type Super struct {
	// GlobalLock 全局锁
	GlobalLock sync.Mutex
}

// waitGlobalLock 等待全局锁定
func (m *Super) waitGlobalLock(f func()) {
	m.GlobalLock.Lock()
	defer m.GlobalLock.Unlock()
	f()
}

// execSingle 执行单行命令，等待命令全部执行完后返回
//
//	param	shell	eg:	`ls	-la`	or	`ps	-ef	|	grep	server`
//	return	string exec result
func execSingle(shell string) (string, error) {
	cmd := exec.Command("/bin/bash", "-c", shell)
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		panic(err)
	}
	defer stdout.Close()

	cmd.Start()

	// 按行读
	reader := bufio.NewReader(stdout)
	result := ""
	for {
		line, err2 := reader.ReadString('\n')
		if err2 != nil || io.EOF == err2 {
			break
		}
		result += line
	}

	cmd.Wait()
	//fmt.Printf("[linuxshell] exec finish: %s\n", shell)
	return result, nil
}
